package demo2String;

import org.junit.Test;

/**
 * @ClassName $ {NAME}
 * @Description TODO
 * @Author shenxinyuan
 * @Date $ {DATE} $ {TIME}
 * @Version 1. 0
 **/

public class LongestCommonPrefix {

    String[] strs = {"flower", "flow", "flight"};
//    String[] strs = {"a"};

        public String longestCommonPrefix(String[] strs) {
            String tmp = "";
            if(strs.length==1){
                return strs[0];
            }
            for (int i = 1; i < strs.length; i++) {
                if(i==1){
                    tmp = commonString(strs[0],strs[i]);
                }else {
                    tmp = commonString(tmp,strs[i]);
                }
                if(tmp.equals("")){
                    return "";
                }
            }
            return tmp;
        }
        public String commonString(String str1, String str2) {
            int length = Math.min(str1.length(), str2.length());
            int index = 0;
            while (index < length && str1.charAt(index) == str2.charAt(index)) {
                index++;
            }
            return str1.substring(0, index);
        }

   /*这种方式时间复杂度太高了，内存消耗也多
   public String commonString(String str1, String str2) {
        int n = 0;
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        String res = "";
        if (str1.length() < str2.length()) {
            n = str1.length();
            for (int i = 0; i < n; i++) {
                if (chars1[i] == chars2[i]) {
                    res += chars1[i];
                }else {
                    break;
                }
            }
        } else {
            n = str2.length();
            for (int i = 0; i < n; i++) {
                if (chars1[i] == chars2[i]) {
                    res += chars1[i];
                }else {
                    break;
                }
            }
        }
        return res;
    }*/

    @Test
    public void test() {
        System.out.println("longestCommonPrefix(strs) = " + longestCommonPrefix(strs));
    }
}
